#include "../app.h"
#include "tkl_gpio.h"

static void parent_del_cb(lv_event_t *e)
{
    tkl_gpio_deinit(TUYA_GPIO_NUM_1);
}

static void toggle_handler(lv_event_t *e)
{
    lv_obj_t *obj = lv_event_get_target(e);
    if (lv_obj_has_state(obj, LV_STATE_CHECKED))
    {
        tkl_gpio_write(TUYA_GPIO_NUM_1, TUYA_GPIO_LEVEL_HIGH);
    }
    else
    {
        tkl_gpio_write(TUYA_GPIO_NUM_1, TUYA_GPIO_LEVEL_LOW);
    }
}

static void init_handler(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t *obj = lv_event_get_target(e);
    lv_obj_t *parent = lv_obj_get_parent(obj);

    if (code == LV_EVENT_CLICKED)
    {

        lv_obj_t *btn2 = lv_btn_create(parent);
        lv_obj_align(btn2, LV_ALIGN_CENTER, 0, 40);
        lv_obj_add_flag(btn2, LV_OBJ_FLAG_CHECKABLE);
        lv_obj_set_height(btn2, LV_SIZE_CONTENT);

        lv_obj_t *label = lv_label_create(btn2);
        lv_label_set_text(label, "Toggle");
        lv_obj_center(label);

        lv_obj_add_event_cb(btn2, toggle_handler, LV_EVENT_ALL, NULL);
        lv_obj_add_flag(obj, LV_OBJ_FLAG_HIDDEN);
        lv_obj_add_event_cb(parent, parent_del_cb, LV_EVENT_DELETE, (void *)NULL);
        TUYA_GPIO_BASE_CFG_T out_pin_cfg = {
            .mode = TUYA_GPIO_PUSH_PULL, .direct = TUYA_GPIO_OUTPUT, .level = TUYA_GPIO_LEVEL_LOW};
        tkl_gpio_init(TUYA_GPIO_NUM_1, &out_pin_cfg);
    }
}

int app_hw_gpio_1(lv_obj_t *parent)
{

    lv_obj_t *btn1 = lv_btn_create(parent);
    lv_obj_align(btn1, LV_ALIGN_CENTER, 0, -40);
    lv_obj_add_event_cb(btn1, init_handler, LV_EVENT_ALL, NULL);

    lv_obj_t *label = lv_label_create(btn1);
    lv_label_set_text(label, "init");
    lv_obj_center(label);

    return 0;
}
